package cheng.shi.hong;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.*;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class XMlToDoc {


    public static void main(String[] args) throws Exception {
        makeWord();

    }


    static void makeWord() throws Exception {
        /** 初始化配置文件 **/
        Configuration configuration = new Configuration();
        /** 加载文件 **/
        configuration.setDirectoryForTemplateLoading(new File(XMlToDoc.class.getClassLoader().getResource("").getPath()));
        /** 加载模板 **/
        Template template = configuration.getTemplate("children.work.document.xml");
        /** 准备数据 **/
        List<Children> childrenList = new ArrayList<>();
        childrenList.add(new Children("张三", 25, "男"));
        childrenList.add(new Children("李四", 28, "男"));
        childrenList.add(new Children("小红", 22, "女"));
        Map map = new HashMap<>();
        map.put("childrenList", childrenList);


        /** 指定输出word文件的路径 **/
        File tempFile = File.createTempFile(new Long(new Date().getTime()).toString(), ".temp");//创建临时文件
        try {
            FileWriter writer = new FileWriter(tempFile);
            template.process(map, writer);
            writer.flush();
            writer.close();


            ZipInputStream zipInputStream = ZipUtils.wrapZipInputStream(XMlToDoc.class.getClassLoader().getResourceAsStream("children.docx"));
            ZipOutputStream zipOutputStream = ZipUtils.wrapZipOutputStream(new FileOutputStream("C:\\newChildren.docx"));
            String replaceEntryName = "word/document.xml";
            ZipUtils.replaceZipEntry(zipInputStream, zipOutputStream, replaceEntryName, new FileInputStream(tempFile));
            System.out.println("success");

        } catch (Exception e) {


        } finally {
            tempFile.delete();

        }


    }


}
































































